<template>
  <div id="gift">
    <div class="gift">
      <div class="gift__hd">
        <ul class="nav">
          <li v-if="isrecord"><a class="active">兑换记录</a></li>
          <li v-for="title in nav" :key="title.type" v-on:click="switchTitle(title, $event)" v-else>
           <a v-bind:class="{active: title.on}">{{title.name}}</a>
          </li>
        </ul>
      </div>
      <div class="gift__bd">
        
        <!-- 兑换记录列表 -->
        <div v-if="isrecord"> <!-- 处理v-if与v-for不能操作在同一标签 -->
          <div class="recordbox" v-for="exchangelog in exchangelogs" :key="exchangelog.id">
            <div class="recordbox__img">
              <img class="img-radius" :src="exchangelog.src">
            </div>
            <div class="recordbox__txt">
              <span class="txt__count">X {{exchangelog.goods_count}}</span>
              <span class="txt__time">{{exchangelog.created}}</span>
              <span class="txt__state">{{exchangelog.state}}</span>
            </div>
          </div>
        </div>

        <!-- 物品列表 -->
        <div class="giftbox" v-for="gift in gifts" :key="gift.id" @click="giftDetails(gift)" v-else >
          <div class="giftbox__hd flex align-items justify-content">
            <p>{{ gift.name }}</p>
          </div>
          <div class="giftbox__bd flex align-items justify-content">
            <img :src="gift.src">
          </div>
          <div class="giftbox__ft flex align-items justify-content">
            <img class="prize" :src="gift.ins_src"><span>{{ gift.count }}</span>{{gift.item_name}}
          </div>
				</div>
      </div>
    </div>
    <div class="gift__ft">
      <p v-if="isrecord" class="record" @click="record">返回 》</p>
      <p v-else class="record" @click="record">兑换记录 》</p>
      <div class="prizes">
        <p class="prizes__yb flex align-items justify-content" v-for="prize in prizes" :key="prize.type" v-if="prize.id == '1' || prize.id == '5'">
          <img class="prize" :src="prize.src">{{prize.name}}
          <span>{{prize.count}}</span>
        </p>
      </div>
    </div>

    <!-- 兑换详情[ 弹框 ] -->
    <div class="modals" id="modals1" v-if="ismodal">
        <!-- <div class="modals__mask"></div> -->
        <div class="modal">
          <span class="close" @click="close">×</span>
          <!-- modal1 -->
          <div class="modal__body" v-if="ismodals.ismodal1">
            <div class="modal__hd flex align-items justify-content">
              <div class="modal-hd__img">
                <img :src="details.src">
              </div>
              <div class="modal-hd__txt">
                <h3>{{details.name}}</h3>
                <p v-if="details.type=='6'">可用于游戏互动</p>
                <p v-else-if="details.type=='4'">可用于参加比赛</p>
                <p v-else-if="details.type=='5'&&details.ins[0].valueid=='6'">用于兑换红包</p>
                <p v-else-if="details.type=='5'&&details.ins[0].valueid!='6'">
                  <!-- 实现路由跳转 -->
                  <router-link class="notice" to="/notice"></router-link>
                </p>
              </div>
            </div>
            <div class="modal__bd">
              <!-- 模态框内容 -->
              <div class="line"></div>
							<p class="modal__bd-count">兑换数量</p> 
              <div class="modal-form flex align-items justify-content">
                <span class="minus" @click="minus"></span>                
                <input @keyup='input' class="count-input" :disabled="Number(max) == 0" v-model="inputCount"  id="count" name="count" :value="inputCount" type="number">
                <span class="add" @click="add"></span>
							</div>
              <p class="modal__bd-notice">
                注：最多还可兑换
                <span class="red">{{residue}}{{details.unit}}</span>
                <span class="red" v-if="details.goods_type==1&&details.ins[0].valueid!=6"> 
                ，库存剩余 {{ details.outs[0].inventory }} {{details.unit}}</span>.
              </p> 
            </div>
            <div class="modal__ft">
                <button class="btn btn__submit flex align-items justify-content" @click="opens(2)" :disabled="Number(max) == 0">
                  <img class="prize" :src="details.ins_src"><span>{{ details.count }}</span>{{details.item_name}}
                </button>
            </div>
          </div>
          <!-- modal2 -->
          <div class="modal__body" v-if="ismodals.ismodal2">
            <div class="modal__hd">
              <div class="modal2__img">
                <img :src="details.src">
              </div>
            </div>
            <div class="modal__bd">
              <p class="modal2__txt">
							  你确定使用
								<span>{{inputCount*details.count}}{{details.unit}}</span>
								<span>{{details.item_name}}</span>,兑换
								<span>{{inputCount}}</span>{{details.unit}}
								<span>{{details.name}}</span>吗？
              </p>
            </div>
            <div class="modal__ft">
                <a href="javascript:;" class="btn btn__cancel" @click="close"></a>
                <a href="javascript:;" class="btn btn__confirm" @click="submit(details.exchangeid,inputCount)"></a>
            </div>
          </div>
          <!-- modal3 -->
          <div class="modal__body" v-if="ismodals.ismodal3">
            <div class="modal__hd">
              <div class="modal3__img" v-if="msg == ''">
                <img :src="details.src">
              </div>
            </div>
            <div class="modal__bd">
              <p class="modal3__txt" v-if="msg != ''">
                {{msg}}
              </p>
              <p class="modal3__txt" v-else>
							  你成功使用
								<span>{{inputCount*details.count}}{{details.unit}}</span>
								<span>{{details.item_name}}</span>,兑换了
								<span>{{inputCount}}</span>{{details.unit}}
								<span>{{details.name}}</span>！
                <span>请到背包中查看使用!</span>
              </p>
            </div>
            <div class="modal__ft">

            </div>
          </div>
        </div>
    </div>

  </div>
</template>

<script>
import qs from "qs";
import axios from 'axios'
import utils from '../../scripts/utils'
export default {
   data(){
     return{
        nav: [{type: 'all',on: true,name: '全部'}, 
              {type: 6,on: false,name: '表情'}, 
              {type: 4,on: false,name: '门票'}, 
              {type: 5,on: false,name: '实物'}],
        type:{},
        gifts: [],
        prizes:[],
        exchangelogs:[],
        details:[],
        isrecord:false, //是否显示兑换记录
        ismodal:false,  //是否显示弹框
        ismodals:{
          ismodal1:false, //弹框1显示
          ismodal2:false, //弹框2显示
          ismodal3:false, //弹框3显示
        },
        inputCount:0,
        max:0,
        residue:0,
        exrate:0,
        msg:'',
      }
   },
   created(){ //在一个实例被创建之后执行代码
     //初始化数据
     this.getGift()
    },
   methods: {
      getGift:function(navtype){
       axios.post('/api/mobile/gift')
        .then((res) => {
          //清空一下数据以免重复
          this.gifts=[];
					//exchanges是商店中的物品信息
          if(res.data != ''){
            res.data.exchanges.forEach((g,index)=> {
              this.type[g.type] = true;
              if(!navtype)this.gifts.push(g);
              else if(navtype=='all')this.gifts.push(g);
              else if(g.type == navtype)this.gifts.push(g);
              g.src = require('../images/goods/' + g.outs[0].valueid + '.png');
              g.ins_src = require('../images/goods/' + g.ins[0].valueid + '.png');
            });
            //遍历货币
            this.prizes = res.data.prizes
            this.prizes.forEach(function (p,index) {
              p.src = require('../images/goods/' + p.id + '.png');
            });
          }
          // 处理tab导航
          this.type = Object.keys(this.type);
          if(this.type.indexOf("4") === -1) this.del(4);
          if(this.type.indexOf("5") === -1) this.del(5);
          if(this.type.indexOf("6") === -1) this.del(6);
        })
        .catch(function (error) {
          console.log(error);
        });
        //处理没有token时的显示
        // if(this.gifts.length == 0) this.nav.splice(1,3);
     },
    getExchangelog:function(){
      axios.post('/api/mobile/exchangelog')
      .then((res) => {
        if(res.data instanceof Array){
          this.exchangelogs = res.data
          //便利兑换记录
				  this.exchangelogs.forEach((e,index)=> {
            //大礼包显示的图片与其他分开显示
            if(e.items.outs[0]&&e.items.outs.length<=1){
              e.src = require('../images/goods/' + e.items.outs[0].id + '.png');
              e.state = '已提交'
            }else{
              e.src = require('../images/goods/' + e.items.ins[0].id + '.png');
              e.state = '已成功' 
            }
          });
        }
      })
      .catch(function (error){
        console.log(error);
      });
    },
    //去除tab未存在
    del(index){
      this.nav.forEach( (t) =>{
        if(t.type == index){
          this.nav.splice(this.nav.indexOf(t),1);
        }
      })
    },
    switchTitle(title, event) {
        //切换标题
        for (let item in this.nav) {
            if (this.nav.hasOwnProperty(item)) {
                let element = this.nav[item]
                element.on = false
                element.type === title.type && (element.on = true)
            }
        }
        //触发筛选
        this.getGift(title.type)
    },
    giftDetails(obj){
      this.opens(1);
      this.details = obj;
      let prize = {};
      //表单中的累加
      //a:accumulator为累加值
      //v:currentValue当前遍历的值
      //i:当前遍历的索引
       this.exrate = Math.abs(this.details.ins.reduce(function (a, v, i) {
				return v.count + a;
      }, 0));
      // 判断货币类型
			for(let g = 0;g<this.prizes.length;g++){
				if (this.details.ins[0].valueid==this.prizes[g].id) prize = this.prizes[g];
			}
			if(!prize.count) prize.count = 0;
      //计算最大兑换数量
      this.max = Math.floor(prize.count / this.exrate) //最多可以兑换的数量

      if(this.max > 0){
        this.inputCount = 1;
        this.residue = this.max-1;
      }else{
        this.inputCount = 0;
        this.residue = this.max;
      }
    },
    add(){
      if(this.inputCount<this.max){
         this.inputCount++
         this.residue--
      }
    },
    minus(){
      if(this.inputCount>0){
        this.inputCount--
        this.residue++
      }
    },
    input(){
      this.inputCount = this.inputCount.replace(/\./g,"");
      if(1<Number(this.inputCount)&&Number(this.inputCount)<this.max){
        this.residue = this.max - this.inputCount;
      }else if(Number(this.inputCount)>this.max){
        this.inputCount = this.max;
        this.residue = 0;
      }else{
        this.inputCount = 1 ;
        this.residue = this.max-1;
      }
    },
     submit(id,count){
      this.opens(3)
      this.msg = ''
      axios.post('/api/mobile/exchangegift',
      qs.stringify({
        exchangeid:id,
        count:count
      }),{
        headers: {
          "Content-Type":
            "application/x-www-form-urlencoded; charset=UTF-8"
        }
      })
      .then((res) => {
        console.log(res);
        if(res.data.error)this.msg = '可能是网络访问故障.'
      })
      .catch(function(err){
        console.log(err);
        this.msg = res.data.message 
      });
    },
    record(){ //兑换记录显示
      if(this.isrecord == true){
        // this.getGift('all');
        this.isrecord = false;
      }else{
        this.getExchangelog();
        this.isrecord = true;
      }
    },
    close(){//关闭弹框
       this.ismodal = false;
    },
    opens(id){
      this.ismodal = true;
      if(id){
        for (var i = 1; i < 4; i++) {
          if(id == i)this.ismodals['ismodal'+i] = true;
          else this.ismodals['ismodal'+i] = false;
        }
      }
    }
   }
}
</script>

<style scoped>

/* public */

/* flax布局 */
.flex{ /*开启弹性布局*/
  display:-webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}
.justify-content{ /*水平居中*/
  -webkit-justify-content:center;
  justify-content:center;
  -moz-box-pack:center;
  -webkit--moz-box-pack:center;
  box-pack:center;
}
.align-items{/*竖直居中*/
  align-items:center;
  -webkit-align-items:center;
  box-align:center;
  -moz-box-align:center;
  -webkit-box-align:center;
}

/* gift-style */

#gift{
  height:100%;
  position:relative;
  overflow: hidden;
  color:#fff;
  background: url('../images/bg.png') no-repeat;
  background-size: 100% 100%;
}
.gift{
    height: 85%;
    overflow: hidden;
    margin:.4rem .3rem .2rem;
    background-color: rgba(120, 170, 160, .4);
    border-radius: 0.2rem;
    border: 0.05rem solid rgba(255, 255, 255, .2);
}
.gift__hd{
  height:10%
}
ul.nav{
    overflow:hidden;
    border-bottom: 0.02rem solid rgb(182, 211, 233);
    margin: 0 .2rem;
    padding: 0 .2rem;
}
.nav>li {
    float: left;
    font-size:16px;
    line-height:1rem;
}
.nav>li>a{
    padding:.05rem .2rem;
    font-size: .25rem;
}
.nav .active{
  border: 2px solid #fff;
  font-weight: 800;
  font-size: .3rem;
  border-radius: .1rem;
}
.gift__bd{
  height:90%;
  overflow:auto;
}
.giftbox{
  font-size:.2rem;
  width: 30%;
  float:left;
  overflow: hidden;
  background: url('../images/kuangditu001.png') center center no-repeat;
  background-size: 100%;
  height: 26%;
  margin:.5rem 2.5% 0;
}
.giftbox:nth-child(3n+2){
  margin:.5rem 0 0 0;
}

.giftbox__hd,.giftbox__ft{
   height:21%
}
.giftbox__bd{
   height:58%;
}

.giftbox__hd p{
  width:80%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  text-align:center;
}

.giftbox__bd>img{
  max-width:64px;

}
.prize{
  height: .3rem;
  max-height:24px;
  margin-right:0.05rem;
}
.record{
    text-align: right;
    margin: 0 15px .15rem;
    font-size: .25rem;
}

.recordbox{
  font-size:.25rem;
  overflow: hidden;
  line-height: 1rem;
  margin: .25rem .3rem;
  border-bottom: .02rem solid #fff;
}

.recordbox__img,.recordbox__txt{
  float:left;
  overflow:hidden;
}

.recordbox__img{
  width:30%;
  text-align:center;
}
.recordbox__txt{
  width:70%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.recordbox__img img{
  max-height:1rem;
}
.recordbox__txt .txt__time{
  margin:0 0.2rem;
}

.prizes{
  overflow: hidden;
  padding: 0 .1rem;
  font-size:.25rem;
  line-height:.5rem;
}
.prizes__yb,.prizes__fk{
  width:50%;
  float:left;
  background: url('../images/tongzhilan1.png') center center no-repeat;
  background-size: 100%;
}

.prizes__yb span{
  margin:0 0.1rem;
}

/* 弹框样式 */
.modals{
  font-size:0.3rem;
}
.modals__mask{
  position: fixed;
  z-index: 999;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
}

.close{
  width:26px;
  height:26px;
  color: #ccc;
  z-index: 1000;
  font-size: 0.7rem;
  right: 0.3rem;
  opacity: .8;
  line-height: 26px;
  position: absolute;
  font-weight: bolder;
  top: 2px;
}

.modal{
  position: fixed;
  z-index: 1000;
  width: 85%;
  max-width: 350px;
  top: 40%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.2);
  text-align: center;
  border-radius: .1rem;
  overflow: hidden;
  padding:0 1em;
}

.modal__body{
  background: url('../images/diwen1.png') center no-repeat;
  background-color: #fff;
  background-size: 50%;
  background-position-y: 100%;
  background-position-x: 0;
}

.modal__hd,.modal__ft{
  padding: 0.5em 1.6em;
  overflow: hidden;
}
.modal__bd{
  padding: 0 1.6em 0.8em;
  min-height: 40px;
  line-height: 1.3;
  word-wrap: break-word;
  word-break: break-all;
}
.modal__ft{
  position: relative;
}

.btn{
  min-height: 50px;
  outline: none;
  border: none;
}

.btn__submit{
  width:60%;
  background: url('../images/konganniu3.png') center center /80% 100% no-repeat;
  margin:auto;
  font-size:.3rem;
  line-height: 0;
  color:#fff;
}
.btn__confirm{
  background: url('../images/queding1.png'), url('../images/konganniu3.png');
}

.btn__cancel{
    background: url('../images/quxiao1.png'), url('../images/konganniu3.png');
}
.btn__confirm,.btn__cancel{
  width:50%;
  float:left;
  background-size: 45%, 70%;
  background-repeat: no-repeat;
  background-position: center;
}

/* 弹框内容 */
.modal-hd__img,.modal-hd__txt{
  float:left;
}
.modal-hd__img{
width:20%;
}
.modal-hd__img img{
  max-width:64px;
}
.modal-hd__txt{
  width:80%;
  padding-left:20px;
  text-align: left;
}
.modal-hd__txt h3,.modal-hd__txt p{
  line-height: .6rem
}
.modal-hd__txt h3{
  font-weight: 400;
  color: #00314C;
  font-size: .3rem;
}
.modal-hd__txt p{
  color: #f00;
  font-size: .25rem;
}

.line{
  background: transparent url('../images/gexian01.png') center center /100% no-repeat;
  height: .5rem;
}
.modal__bd-count{
  width:50%;
  padding:.2rem;
  margin:.1rem auto;
  font-size:.2rem;
  background: url('../images/goumaishuliangdi.png') center center /100% no-repeat;
}

.modal-form{
 height: 0.7rem;
 margin: auto;
}

.add,.minus{
  width: 15%;
  height: .5rem;
  padding: 6px 12px;
}
.add{
  background: url('../images/shuzijia1.png') center /110% 120% no-repeat;
}
.minus{
background: url('../images/shuzijian1.png') center /110% 120% no-repeat;
}
.count-input{
  width: 70%;
  height: .5rem;
  border: none;
  background: rgba(0, 0, 0, 0.2);
  font-size: 0.3rem;
  padding: 6px 12px;
  text-align:center;
  outline:none;
  color:#555;
}

.modal__bd-notice{
  color: #f00;
  text-align: center;
  font-size: 0.25rem;
  margin:.3rem .1rem 0;
}

.modal2__img img,.modal3__img img{
  max-height:64px
}

p.modal2__txt,p.modal3__txt{
  color:#000;
  line-height:.5rem
}
a.notice{
  display: inline-block;
  width: 70%;
  height: 0.8rem;
  background: url('../images/duihuan01.png') center /90% no-repeat;
}
</style>
